function data = iq_read_data(file, type_)     % -*- octave -*-
handle = fopen(file, "rt");
cookie = fgetl(handle);
bad = 0;
switch type_
  case "sparse boolean matrix", 
    if strcmp(cookie, "# IQ sparse boolean matrix format 0.1"), 
      data = read_sparse_boolean(handle); 
    else,
      bad = 1;
    endif
  case "sparse float matrix",
    if strcmp(cookie, "# IQ sparse real matrix format 0.1"),
      data = read_sparse_float(handle); 
    else,
      bad = 1;
    endif
  case "dense float matrix",
    if strcmp(cookie, "# IQ dense real matrix format 0.1"),
      data = read_dense_float(handle); 
    else,
      bad = 1;
    endif
  otherwise,
    error("Unknown data type: %s", type_);
endswitch;
if bad,
  error([file ": expected " type_ ", got file with cookie:\n" cookie "\n"]);
  data = [];
endif
fclose(handle);
endfunction

function [data] = read_sparse_boolean(handle);
[r c] = read_rows_cols(handle);
data = sparse(r, c);
for i=1:r,
  line = fgetl(handle);
  where = sscanf(line, "%d");
  data(i,where+1) = 1;
endfor
endfunction

function [data] = read_sparse_float(handle);
[r c] = read_rows_cols(handle);
data = sparse(r, c);
for i=1:r,
  line = fgetl(handle);
  rowdata = sscanf(line, "%d:%f", [2, Inf]);
  data(i,rowdata(1,:)+1) = rowdata(2,:);
endfor
endfunction

function [data] = read_dense_float(handle);
[r c] = read_rows_cols(handle);
data = zeros(r,c);
for i=1:r,
  line = fgetl(handle);
  data(i,:) = sscanf(line, "%f", c);
endfor
endfunction

function [r c] = read_rows_cols(handle)
line = fgetl(handle);
r = sscanf(line, "# rows: %d\n", 1);
line = fgetl(handle);
c = sscanf(line, "# columns: %d\n", 1);
endfunction

